package com.example.javabasic.thread.classtwo.threadpermessage.demo3;

import java.io.*;
import java.net.Socket;
//客户端执行任务
public class ClientHandler implements Runnable {
    private final Socket socket;
    private volatile boolean running = true;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream();
             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
             PrintWriter pr = new PrintWriter(outputStream)) {

            while (running) {
                String message= br.readLine();
                System.out.println("接收到消息->"+message);
                pr.write(message);
                pr.flush();
            }
        } catch (IOException e) {
            this.running = false;
        }
    }


    public void stop() {
        if (!running) {
            return;
        }
        this.running = false;
        try {
            this.socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
